/*This file is part of SpatialTest.

SpatialTest is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

SpatialTest is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with SpatialTest.  If not, see <http://www.gnu.org/licenses/>.*/

package andresenspatialtest;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

/**
 * Graphical interface to the SpatialTestAlg, used to run Martin Andressen's
 * spatial point pattern test.
 * @author Nick Malleson
 */
public class SpatialTestGUI extends javax.swing.JFrame {

    /** Creates new form SpatialTestGUI */
    public SpatialTestGUI() {
        initComponents();
    }
    private File baseFile;
    private File testFile;
    private File areaFile;
    private File outputAreaFile;

    // Always use same file chooser throughout program (remembers current dir etc)
    private JFileChooser chooser = null;

    // File which saves parameters
    private File parametersFile = null;
    private final String PARAMS_FILENAME = "params.txt";

    private void createFileChooser() {
        if (this.chooser == null) {
            this.chooser = new JFileChooser(".");
            ExampleFileFilter filter = new ExampleFileFilter();
            filter.addExtension("shp");
            filter.setDescription("ESRI Shapefiless");
            chooser.setFileFilter(filter);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        bastFilenameLabel = new javax.swing.JLabel();
        testFilenameLabel = new javax.swing.JLabel();
        areaFilenameLabel = new javax.swing.JLabel();
        testFilename = new javax.swing.JTextField();
        areaFilename = new javax.swing.JTextField();
        baseFilename = new javax.swing.JTextField();
        browseBaseFile = new javax.swing.JButton();
        browseAreaFile = new javax.swing.JButton();
        browseTestFile = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        bastFilenameLabel1 = new javax.swing.JLabel();
        outputAreaFilename = new javax.swing.JTextField();
        browseOutputArea = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        exitButton = new javax.swing.JButton();
        clearButton = new javax.swing.JButton();
        runAlgButton = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        bastFilenameLabel2 = new javax.swing.JLabel();
        monteCarloRunField = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        bastFilenameLabel3 = new javax.swing.JLabel();
        sampleSizeRunField = new javax.swing.JTextField();
        saveParamsButton = new javax.swing.JButton();
        loadParamsButton = new javax.swing.JButton();
        icursLogoLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBackground(new java.awt.Color(153, 153, 255));
        jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED, java.awt.Color.white, java.awt.Color.white, java.awt.Color.black, java.awt.Color.black));

        bastFilenameLabel.setText("Base Dataset");

        testFilenameLabel.setText("Test Dataset");

        areaFilenameLabel.setText("Area Dataset");

        testFilename.setEditable(false);

        areaFilename.setEditable(false);

        baseFilename.setEditable(false);
        baseFilename.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                baseFilenameActionPerformed(evt);
            }
        });

        browseBaseFile.setText("browse");
        browseBaseFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                browseBaseFileActionPerformed(evt);
            }
        });

        browseAreaFile.setText("browse");
        browseAreaFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                browseAreaFileActionPerformed(evt);
            }
        });

        browseTestFile.setText("browse");
        browseTestFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                browseTestFileActionPerformed(evt);
            }
        });

        jLabel1.setBackground(new java.awt.Color(204, 204, 204));
        jLabel1.setFont(new java.awt.Font("Lucida Grande", 0, 18));
        jLabel1.setText("Input Shapefiles");

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(bastFilenameLabel)
                            .add(testFilenameLabel)
                            .add(areaFilenameLabel))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                            .add(testFilename)
                            .add(org.jdesktop.layout.GroupLayout.TRAILING, areaFilename)
                            .add(baseFilename, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 271, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(browseBaseFile, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 47, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                                .add(org.jdesktop.layout.GroupLayout.LEADING, browseAreaFile, 0, 0, Short.MAX_VALUE)
                                .add(org.jdesktop.layout.GroupLayout.LEADING, browseTestFile, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 45, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(167, 167, 167)
                        .add(jLabel1)))
                .addContainerGap(94, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
                .add(jLabel1)
                .add(18, 18, 18)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(baseFilename, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(bastFilenameLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 16, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(browseBaseFile))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(testFilename, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(testFilenameLabel)
                    .add(browseTestFile))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(areaFilename, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(areaFilenameLabel)
                    .add(browseAreaFile))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBackground(new java.awt.Color(153, 153, 255));
        jPanel2.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED, java.awt.Color.white, java.awt.Color.white, java.awt.Color.black, java.awt.Color.black));

        bastFilenameLabel1.setText("Area Dataset");

        outputAreaFilename.setEditable(false);
        outputAreaFilename.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                outputAreaFilenameActionPerformed(evt);
            }
        });

        browseOutputArea.setText("browse");
        browseOutputArea.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                browseOutputAreaActionPerformed(evt);
            }
        });

        jLabel2.setBackground(new java.awt.Color(204, 204, 204));
        jLabel2.setFont(new java.awt.Font("Lucida Grande", 0, 18));
        jLabel2.setText("Output Shapefile");

        org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel2Layout.createSequentialGroup()
                        .addContainerGap()
                        .add(bastFilenameLabel1)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(outputAreaFilename, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 271, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(browseOutputArea, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 47, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(jPanel2Layout.createSequentialGroup()
                        .add(158, 158, 158)
                        .add(jLabel2)))
                .addContainerGap(94, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel2Layout.createSequentialGroup()
                .add(jLabel2)
                .add(18, 18, 18)
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(outputAreaFilename, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(bastFilenameLabel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 16, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(browseOutputArea))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        exitButton.setText("Exit");
        exitButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitButtonActionPerformed(evt);
            }
        });

        clearButton.setText("Clear Parameters");
        clearButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clearButtonActionPerformed(evt);
            }
        });

        runAlgButton.setBackground(new java.awt.Color(0, 0, 204));
        runAlgButton.setText("Run Algorithm");
        runAlgButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                runAlgButtonActionPerformed(evt);
            }
        });

        jPanel3.setBackground(new java.awt.Color(153, 153, 255));
        jPanel3.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED, java.awt.Color.white, java.awt.Color.white, java.awt.Color.black, java.awt.Color.black));

        bastFilenameLabel2.setText("Number of Monte Carlo runs");

        monteCarloRunField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                monteCarloRunFieldActionPerformed(evt);
            }
        });
        monteCarloRunField.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                monteCarloRunFieldPropertyChange(evt);
            }
        });

        jLabel4.setBackground(new java.awt.Color(204, 204, 204));
        jLabel4.setFont(new java.awt.Font("Lucida Grande", 0, 18));
        jLabel4.setText("Parameters");

        bastFilenameLabel3.setText("Percentage Sample Size");

        sampleSizeRunField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sampleSizeRunFieldActionPerformed(evt);
            }
        });
        sampleSizeRunField.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                sampleSizeRunFieldPropertyChange(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .add(bastFilenameLabel2)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 69, Short.MAX_VALUE)
                .add(monteCarloRunField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 174, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(89, 89, 89))
            .add(jPanel3Layout.createSequentialGroup()
                .add(167, 167, 167)
                .add(jLabel4)
                .addContainerGap(267, Short.MAX_VALUE))
            .add(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .add(bastFilenameLabel3)
                .add(69, 69, 69)
                .add(sampleSizeRunField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 174, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(122, 122, 122))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel3Layout.createSequentialGroup()
                .add(4, 4, 4)
                .add(jLabel4)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel3Layout.createSequentialGroup()
                        .add(monteCarloRunField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(sampleSizeRunField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(bastFilenameLabel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 16, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                    .add(bastFilenameLabel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 16, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(21, Short.MAX_VALUE))
        );

        saveParamsButton.setText("Save Parameters");
        saveParamsButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveParamsButtonActionPerformed(evt);
            }
        });

        loadParamsButton.setText("Load Parameters");
        loadParamsButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loadParamsButtonActionPerformed(evt);
            }
        });

        icursLogoLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/andresenspatialtest/resources/icursLogo.gif"))); // NOI18N

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(icursLogoLabel)
                    .add(jLabel3)
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                            .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .add(org.jdesktop.layout.GroupLayout.LEADING, runAlgButton, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(exitButton)
                            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                                .add(clearButton, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .add(saveParamsButton, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .add(loadParamsButton)))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(10, 10, 10)
                .add(icursLogoLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(layout.createSequentialGroup()
                        .add(jLabel3)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 161, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(18, 18, 18)
                        .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(18, 18, 18)
                        .add(jPanel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(20, 20, 20)
                        .add(runAlgButton))
                    .add(layout.createSequentialGroup()
                        .add(clearButton)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(saveParamsButton)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(loadParamsButton)
                        .add(18, 18, 18)
                        .add(exitButton)))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void baseFilenameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_baseFilenameActionPerformed
        // Don't need any actions, users aren't able to edit text in the box
        // (it just prints the filename they select)
        return;
}//GEN-LAST:event_baseFilenameActionPerformed

    private void outputAreaFilenameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_outputAreaFilenameActionPerformed
        // Don't need any actions, users aren't able to edit text in the box
        // (it just prints the filename they select)
        return;
}//GEN-LAST:event_outputAreaFilenameActionPerformed

    private void exitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitButtonActionPerformed
        System.exit(0);
    }//GEN-LAST:event_exitButtonActionPerformed

    private void clearButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearButtonActionPerformed

        this.baseFilename.setText("");
        this.testFilename.setText("");
        this.areaFilename.setText("");
        this.outputAreaFilename.setText("");
        this.monteCarloRunField.setText("");
        this.sampleSizeRunField.setText("");
        this.baseFile = null;
        this.testFile = null;
        this.areaFile = null;
        this.outputAreaFile = null;
        // Also delete the parameters file (if it exists)
        if (this.parametersFile == null) {
            this.parametersFile = new File(this.PARAMS_FILENAME);
        }
        if (this.parametersFile.exists()) {
            this.parametersFile.delete();
        }
        JOptionPane.showMessageDialog(this, "Cleared parameters and deleted parameters file.");
}//GEN-LAST:event_clearButtonActionPerformed

    private void browseBaseFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseBaseFileActionPerformed

        this.createFileChooser(); // Create the file chooser (if it is null)
        this.chooser.setDialogTitle("Choose base data points shapefile");
        int returnVal = chooser.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            System.out.println("You chose to open the base points file: " +
                    chooser.getSelectedFile().getName());
            this.baseFile = chooser.getSelectedFile();
            this.baseFilename.setText(chooser.getSelectedFile().getName());
        }
    }//GEN-LAST:event_browseBaseFileActionPerformed

    private void browseTestFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseTestFileActionPerformed
        this.createFileChooser(); // Create the file chooser (if it is null)
        this.chooser.setDialogTitle("Choose base data points shapefile");
        int returnVal = chooser.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            System.out.println("You chose to open the test points file: " +
                    chooser.getSelectedFile().getName());
            this.testFile = chooser.getSelectedFile();
            this.testFilename.setText(chooser.getSelectedFile().getName());
        }
    }//GEN-LAST:event_browseTestFileActionPerformed

    private void browseAreaFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseAreaFileActionPerformed
        this.createFileChooser(); // Create the file chooser (if it is null)
        this.chooser.setDialogTitle("Choose base data points shapefile");
        int returnVal = chooser.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            System.out.println("You chose to open the input area file: " +
                    chooser.getSelectedFile().getName());
            this.areaFile = chooser.getSelectedFile();
            this.areaFilename.setText(chooser.getSelectedFile().getName());
        }

    }//GEN-LAST:event_browseAreaFileActionPerformed

    private void browseOutputAreaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseOutputAreaActionPerformed
        this.createFileChooser(); // Create the file chooser (if it is null)
        this.chooser.setDialogTitle("Choose base data points shapefile");
        int returnVal = chooser.showSaveDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            System.out.println("You chose to save the area shapefile to: " +
                    chooser.getSelectedFile().getName());
            String name = chooser.getSelectedFile().getName();
            // Check the file ends in '.shp'
            if (!name.substring(name.length()-4, name.length()).equals(".shp")) {
                this.outputAreaFile = new File(chooser.getSelectedFile().getAbsoluteFile()+".shp");
                this.outputAreaFilename.setText(this.outputAreaFile.getName());
            }
            else {
                this.outputAreaFile = chooser.getSelectedFile();
                this.outputAreaFilename.setText(chooser.getSelectedFile().getName());
            }
        }

    }//GEN-LAST:event_browseOutputAreaActionPerformed

    private void runAlgButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_runAlgButtonActionPerformed
        // TODO Check files are valid.
        if (this.getMonteCarloNum()==-1) {
            JOptionPane.showMessageDialog(this,"Please enter a Monte-Carlo number to run the simulation.");
            return;
        }
        if (this.getSampleSizeNum()==-1) {
            JOptionPane.showMessageDialog(this,"Please enter percentage sample size (integer).");
            return;
        }
        SpatialTestAlg st = new SpatialTestAlg(
                this.baseFile,
                this.testFile,
                this.areaFile,
                this.outputAreaFile,
                this.getMonteCarloNum());
        st.setSamplePercentage(this.getSampleSizeNum());
        boolean success = st.runAlgorithm();

        if (success) {
            JOptionPane.showMessageDialog(this,"All finished successfully.\n" +
                    "Found global S value: "+st.getGlobalS()+"\n"+
                    "Output areas file written to:\n\t"+
                    this.outputAreaFile.getAbsoluteFile().toString()+"");
        }
        else {
            JOptionPane.showMessageDialog(this,"There was an error running the algorithm.");
        }
}//GEN-LAST:event_runAlgButtonActionPerformed

    private void monteCarloRunFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_monteCarloRunFieldActionPerformed
//          try {
//              int num = Integer.parseInt(this.monteCarloRunField.getText());
//        } catch (NumberFormatException e) {
//        }
//        System.out.println("Changed Monte-Carlo value: "+this.monteCarloRunField.getText()+
//                " ("+this.monteCarloRunField.getText()+")");
}//GEN-LAST:event_monteCarloRunFieldActionPerformed

    private void monteCarloRunFieldPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_monteCarloRunFieldPropertyChange
//        try {
//            this.monteCarloNum = Integer.parseInt(this.monteCarloRunField.getText());
//        } catch (NumberFormatException e) {
//            // Used didn't enter an integer number
//            this.monteCarloNum = -1;
//        }
//        System.out.println("Changed Monte-Carlo value: "+this.monteCarloNum+
//                " ("+this.monteCarloRunField.getText()+")");
    }//GEN-LAST:event_monteCarloRunFieldPropertyChange

    /* Write the current parameters to a file */
    private void saveParamsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveParamsButtonActionPerformed
        if (this.parametersFile != null && this.parametersFile.exists()) {
            this.parametersFile.delete();
        }
        this.parametersFile = new File(this.PARAMS_FILENAME);
        try {
            BufferedWriter writer = new BufferedWriter(new FileWriter(this.parametersFile));
            writer.write("# This file stores program parameters to make it quicker to load a " +
                    "a test many times.\n# You can edit the filenames after a '$'\n");
            writer.write("base points$" +
                    (this.baseFile == null ? "\n" : this.baseFile.getAbsolutePath().toString() + "\n"));
            writer.write("test points$" +
                    (this.testFile == null ? "\n" : this.testFile.getAbsolutePath().toString() + "\n"));
            writer.write("area input$" +
                    (this.areaFile == null ? "\n" : this.areaFile.getAbsolutePath().toString() + "\n"));
            writer.write("area output$" +
                    (this.outputAreaFile == null ? "\n" : this.outputAreaFile.getAbsolutePath().toString() + "\n"));
            writer.write("monte carlo$" +
                    (this.getMonteCarloNum() == -1 ? "" : this.getMonteCarloNum()));
            writer.close();
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this, "I/O error writing parameters file.");
        }
        JOptionPane.showMessageDialog(this, "Saved parameters.");
    }//GEN-LAST:event_saveParamsButtonActionPerformed

    private void loadParamsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadParamsButtonActionPerformed
        if (this.parametersFile == null) {
            this.parametersFile = new File(this.PARAMS_FILENAME);
        }
        if (!this.parametersFile.exists()) {
            JOptionPane.showMessageDialog(this, "I don't think you've saved any parameters yet.");
            return;
        }
        try {
            // The parameters file exists, try to load and parse it.
            BufferedReader reader = new BufferedReader(new FileReader(this.parametersFile));
            for (String line = reader.readLine(); line != null; line = reader.readLine()) {
                if (!line.startsWith("#")) { // ignore comments
                    // Split on the dollar
                    String[] lineSplit = line.split("\\$");
//                    if (lineSplit.length != 2) {
//                        JOptionPane.showMessageDialog(this, "Error reading line in parameters file:\n " +
//                                "'"+line+"'\n"+"I couldn't split the line into two parts on the colon.");
//                    }
                    if (lineSplit[0].equals("base points")) {
                        if (lineSplit.length > 1 )
                            if (this.setFile(lineSplit[1], this.baseFilename) )
                                this.baseFile = new File(lineSplit[1]);
                    } else if (lineSplit[0].equals("test points")) {
                        if (lineSplit.length > 1 )
                            if (this.setFile(lineSplit[1], this.testFilename))
                                this.testFile = new File(lineSplit[1]);
                    } else if (lineSplit[0].equals("area input")) {
                        if (lineSplit.length > 1 )
                            if (this.setFile(lineSplit[1], this.areaFilename))
                                this.areaFile = new File(lineSplit[1]);
                    } else if (lineSplit[0].equals("area output")) {
                        if (lineSplit.length > 1 )
                            if (this.setFile(lineSplit[1], this.outputAreaFilename))
                                this.outputAreaFile = new File(lineSplit[1]);
                    } else if (lineSplit[0].equals("monte carlo")) {
                        if (lineSplit.length > 1 ) {
                            try {
                                int mc = Integer.parseInt(lineSplit[1]);
                                this.monteCarloRunField.setText(String.valueOf(mc));
                            } catch (NumberFormatException e) {
                                JOptionPane.showMessageDialog(this, "Could not read Monte-Carlo parameter: " +
                                        lineSplit[1]+". Is it a number?");
                            }
                        }
                    } else {
                        JOptionPane.showMessageDialog(this, "Error reading line in parameters file:" +
                                "\n\t'"+line+"'"+Arrays.toString(lineSplit));
                    }
                } // if line contains ':'
            } // for line in file
            reader.close();
            JOptionPane.showMessageDialog(this, "Loaded parameters.");
        } catch (FileNotFoundException e) {
            JOptionPane.showMessageDialog(this, "Error: couldn't find the parameters file.");
        } catch (IOException e) {
            JOptionPane.showMessageDialog(this, "I/O error reading parameters file.");
        }
    }//GEN-LAST:event_loadParamsButtonActionPerformed

    private void sampleSizeRunFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sampleSizeRunFieldActionPerformed
       // TODO add your handling code here:
    }//GEN-LAST:event_sampleSizeRunFieldActionPerformed

    private void sampleSizeRunFieldPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_sampleSizeRunFieldPropertyChange
       // TODO add your handling code here:
    }//GEN-LAST:event_sampleSizeRunFieldPropertyChange

        /** Convenience method to set a filename */
    private boolean setFile(String inFileName, JTextField theFilename) {
        if (inFileName.length() > 0) { // ignore if filename is empty
            File file = new File(inFileName);
            if (file.exists()) {
                theFilename.setText(file.getName());
                return true;
            } else {
                JOptionPane.showMessageDialog(this,
                        "Couldn't find the file:\n" + file.getAbsolutePath());
            }
        }
        return false;
    }

    /** Gets the monte-carlo number from the text field which users can edit */
    private Integer getMonteCarloNum() {
        Integer num = 0;
        try {
            num = Integer.parseInt(this.monteCarloRunField.getText());
            return num;
        } catch (NumberFormatException e) {
        }
        return -1;
    }

        /** Gets the monte-carlo number from the text field which users can edit */
    private Integer getSampleSizeNum() {
        Integer num = 0;
        try {
            num = Integer.parseInt(this.sampleSizeRunField.getText());
            return num;
        } catch (NumberFormatException e) {
        }
        return -1;
    }


    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException ex) {
            System.err.println("Error setting look and feel");
            ex.printStackTrace();
        } catch (InstantiationException ex) {
            System.err.println("Error setting look and feel");
            ex.printStackTrace();
        } catch (IllegalAccessException ex) {
            System.err.println("Error setting look and feel");
            ex.printStackTrace();
        } catch (UnsupportedLookAndFeelException ex) {
            System.err.println("Error setting look and feel");
            ex.printStackTrace();
        }
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new SpatialTestGUI().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField areaFilename;
    private javax.swing.JLabel areaFilenameLabel;
    private javax.swing.JTextField baseFilename;
    private javax.swing.JLabel bastFilenameLabel;
    private javax.swing.JLabel bastFilenameLabel1;
    private javax.swing.JLabel bastFilenameLabel2;
    private javax.swing.JLabel bastFilenameLabel3;
    private javax.swing.JButton browseAreaFile;
    private javax.swing.JButton browseBaseFile;
    private javax.swing.JButton browseOutputArea;
    private javax.swing.JButton browseTestFile;
    private javax.swing.JButton clearButton;
    private javax.swing.JButton exitButton;
    private javax.swing.JLabel icursLogoLabel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JButton loadParamsButton;
    private javax.swing.JTextField monteCarloRunField;
    private javax.swing.JTextField outputAreaFilename;
    private javax.swing.JButton runAlgButton;
    private javax.swing.JTextField sampleSizeRunField;
    private javax.swing.JButton saveParamsButton;
    private javax.swing.JTextField testFilename;
    private javax.swing.JLabel testFilenameLabel;
    // End of variables declaration//GEN-END:variables

}
